package com.min.netty.codec;

import com.min.netty.model.LogEvent;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * Create By minzhiwei On 2018/9/10 16:52
 */
public class LogEventEncoder extends MessageToMessageEncoder<LogEvent> {
    /**
     *
     */
    final private InetSocketAddress inetSocketAddress;

    public LogEventEncoder(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }


    @Override
    protected void encode(ChannelHandlerContext ctx, LogEvent msg, List<Object> out) throws Exception {
        final ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeBytes(msg.getLogfile().getBytes(CharsetUtil.UTF_8));
        byteBuf.writeByte(LogEvent.SEPARATOR);
        byteBuf.writeBytes(msg.getMsg().getBytes(CharsetUtil.UTF_8));
        out.add(new DatagramPacket(byteBuf, inetSocketAddress));
    }
}
